package com.zlict.commonelasticsearch.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Bean;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.event.EventListener;

import jakarta.annotation.PostConstruct;

/**
 * SSL 证书验证配置类
 * 用于解决 Elasticsearch HTTPS 连接时的证书验证问题
 * 
 * @author zlict
 */
@Configuration
public class SSLConfig {

    /**
     * 应用启动时配置 SSL 证书验证
     * 开发环境跳过证书验证，生产环境请使用有效证书
     */
    @PostConstruct
    public void configureSSL() {
        // 跳过 SSL 证书验证（仅用于开发环境）
        System.setProperty("com.sun.net.ssl.checkRevocation", "false");
        System.setProperty("trust_all_cert", "true");
        
        // 禁用主机名验证
        System.setProperty("com.sun.net.ssl.checkRevocation", "false");
        
        // 设置信任所有证书
        System.setProperty("javax.net.ssl.trustStore", "");
        System.setProperty("javax.net.ssl.trustStorePassword", "");
        
        // 禁用证书路径验证
        System.setProperty("com.sun.net.ssl.checkRevocation", "false");
        System.setProperty("sun.security.ssl.allowUnsafeRenegotiation", "true");
        System.setProperty("sun.security.ssl.allowLegacyHelloMessages", "true");
    }
    
    /**
     * 应用就绪后再次确保 SSL 配置生效
     */
    @EventListener(ApplicationReadyEvent.class)
    public void onApplicationReady() {
        // 确保 SSL 配置在应用启动后生效
        configureSSL();
    }
}
